// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import Vuex from 'vuex';
import product_data from './product';
import './style.css';

Vue.config.productionTip = false;
Vue.use(Vuex);

function getFilterArray(array) {
  const res = [];
  const json = {};
  for (let i = 0; i < array.length; i++) {
    const _self = array[i];
    if (!json[_self]) {
      res.push(_self);
      json[_self] = 1;
    }
  }
  return res;
}

let LocalEvent = function (item) {
  this.get = function () {
    return localStorage.getItem(item);
  };
  this.set = function (val) {
    localStorage.setItem(item, val);
  };
  this.remove = function () {
    localStorage.removeItem(item);
  };
  this.clear = function () {
    localStorage.clear();
  };
};

let cartListStorage = new LocalEvent('storageList');

const store = new Vuex.Store({
  state: {
    productList: [],
    cartList: JSON.parse(cartListStorage.get())
  },
  getters: {
    brands: state => {
      const brands = state.productList.map(item => item.brand);
      return getFilterArray(brands);
    },
    colors: state => {
      const colors = state.productList.map(item => item.color);
      return getFilterArray(colors);
    }
  },
  mutations: {
    addCart(state, id) {
      const isAdded = state.cartList.find(item => item.id === id);
      if (isAdded) {
        isAdded.count++;
      } else {
        state.cartList.push({
          id: id,
          count: 1
        });
      }
      cartListStorage.set(JSON.stringify(state.cartList));
    },
    setProductList(state, data) {
      state.productList = data;
    },
    editCartCount(state, payload) {
      const product = state.cartList.find(item => item.id === payload.id);
      product.count += payload.count;
      cartListStorage.set(JSON.stringify(state.cartList));
    },
    deleteCart(state, id) {
      const index = state.cartList.findIndex(item => item.id === id);
      state.cartList.splice(index, 1);
      cartListStorage.set(JSON.stringify(state.cartList));
    },
    emptyCart(state) {
      state.cartList = [];
      cartListStorage.set(JSON.stringify(state.cartList));
    }
  },
  actions: {
    getProductList(context) {
      setTimeout(() => {
        context.commit('setProductList', product_data);
      }, 500);
    },
    buy(context) {
      return new Promise(resolve => {
        setTimeout(() => {
          context.commit('emptyCart');
          resolve();
        }, 500)
      })
    }
  }
});

import router from './router'

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  store,
  components: { App },
  template: '<App/>'
});
